//
//  Match.m
//  Soccer
//
//  Created by Hyun-Woong Kim on 09. 04. 29.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "Match.h"
#import "NetworkManager.h"
#import "Constant.h"

@implementation Match

@synthesize myself;
@synthesize delegate = _delegate;
@synthesize players;
@synthesize ball_;
@synthesize stadium = stadium_;
@synthesize miniMap =  miniMap_;
@synthesize shakedNum;
@synthesize initDate;
@synthesize goal_teamA;
@synthesize goal_teamB;

- (id)init
{
	if (self = [super init])
	{
		stadium_ = nil;
		ball_ = nil;
		cameraPosition = CGPointZero;
		players = [[NSMutableArray arrayWithCapacity:12] retain];
		
		goal_teamA = 0;
		goal_teamB = 0;
		
		// 시간을 표시하는 레이블
		gameTimeView = [[UITextView alloc] initWithFrame:CGRectMake(200.0f, 0.0f, 80.0f, 30.0f)];
		gameTimeView.textAlignment = UITextAlignmentCenter;
		[gameTimeView setText:@"Time 0 : 0"];
		gameTimeView.editable = NO;
		[[Director sharedDirector].openGLView addSubview:gameTimeView];
		
		// 골을 표시하는 레이블
		goalView = [[UITextView alloc] initWithFrame:CGRectMake(200.0f, 290.0f, 120.0f, 30.0f)];
		goalView.textAlignment = UITextAlignmentCenter;
		[goalView setText:@"Red 0 : 0 Blue"];
		goalView.editable = NO;
		[[Director sharedDirector].openGLView addSubview:goalView];
		
//		// Latency 측정
//		latencyView = [[UITextView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 120.0f, 30.0f)];
//		latencyView.textAlignment = UITextAlignmentCenter;
//		[latencyView setText:@"Latency "];
//		latencyView.editable = NO;
//		[[Director sharedDirector].openGLView addSubview:latencyView];
	}
	return self;
}

- (void)dealloc
{
	[stadium_ release];
	[ball_ release];
	[players release];
	[super dealloc];
}

- (Stadium *)getStadium
{
	return stadium_;
}

- (void)setStadium:(Stadium *)stadium
{
	stadium_ = stadium;
	[stadium_ retain];
	[_delegate objectAdded:stadium_];
}

- (MiniMap *)getMinimap
{
	return miniMap_;
}

- (void)setMiniMap:(MiniMap *)miniMap
{
	miniMap_ = miniMap;
	[miniMap_ retain];
	[_delegate objectAdded:miniMap_];
}

- (void)addObject:(Object *)object
{
	[_delegate objectAdded:object];
}

- (void)addPlayer:(Player *)player
{
	if ([player isKindOfClass:[GoalKeeper class]])
	{
		if (player.team == TeamA)
		{
			((GoalKeeper *)player).goalPostBounds = stadium_.teamAGoalPostBounds;
			player.position = stadium_.teamAGoalPostBounds.origin;
		}
		else
		{
			((GoalKeeper *)player).goalPostBounds = stadium_.teamBGoalPostBounds;
			player.position = CGPointMake(stadium_.teamBGoalPostBounds.origin.x + stadium_.teamBGoalPostBounds.size.width, stadium_.teamBGoalPostBounds.origin.y);
		}
		player.dirRad = kPi / 2;
		player.isMoving = YES;
	}
	[players addObject:player];
	[_delegate objectAdded:player];
}

- (void)setBall:(Ball *)ball
{
	ball_ = ball;
	[ball_ retain];
	[_delegate objectAdded:ball_];
}

- (void)adjustCameraPosition:(CGPoint)playerPosition
{
	CGSize screenSize = [[Director sharedDirector] displaySize];
	
	CGFloat x = playerPosition.x;
	if (x < screenSize.width / 2)
		x = screenSize.width / 2;
	else if (x > stadium_.size.width - screenSize.width / 2)
		x = stadium_.size.width - screenSize.width / 2;
	
	CGFloat y = playerPosition.y;
	if (y < screenSize.height / 2)
		y = screenSize.height / 2;
	else if (y > stadium_.size.height - screenSize.height / 2)
		y = stadium_.size.height - screenSize.height / 2;
	
	cameraPosition = CGPointMake(x, y);
}

- (CGPoint)getCameraPosition
{
	return cameraPosition;
}

- (CGPoint)checkOutline:(CGPoint)position
{
	CGPoint newPosition = position;
	CGPoint origin = stadium_.groundBounds.origin;
	CGSize size = stadium_.groundBounds.size;
	if (position.x < origin.x)
	{
		newPosition.x = origin.x;
	}
	else if (position.x > origin.x + size.width)
	{
		newPosition.x = origin.x + size.width;
	}
	
	if (position.y < origin.y)
	{
		newPosition.y = origin.y;
	}
	else if (position.y > origin.y + size.height)
	{
		newPosition.y = origin.y + size.height;
	}
	
	return newPosition;
}

- (int) getGoalA
{
	return goal_teamA;
}

- (int) getGoalB
{
	return goal_teamB;
}

// 주어진 인덱스의 플레이어 포지션 값을 리턴한다
- (CGPoint)getPlayerPositionAt:(int)index
{
	Player *tempPlayer = [players objectAtIndex:index];
	CGPoint tempPosition = tempPlayer.position;
	
	return tempPosition;
}

// 주어진 인덱스의 플레이어 방향 값을 리턴한다
- (double)getPlayerDirectionAt:(int)index
{
	Player *tempPlayer = [players objectAtIndex:index];
	double tempDirection = tempPlayer.dirRad;
	
	return tempDirection;
}

// 주어진 인덱스의 플레이어 상태 값을 리턴한다
- (PlayerStatus) getPlayerStatusAt:(int)index
{
	Player *tempPlayer = [players objectAtIndex:index];
	PlayerStatus tempStatus = tempPlayer.status;
	
	return tempStatus;
}

// 볼의 포지션 값을 리턴한다
- (CGPoint)getBallPosition
{
	Ball *tempBall = ball_;
	CGPoint tempPosition = tempBall.position;
	
	return tempPosition;
}

// 볼의 방향 값을 리턴한다
- (double)getBallDirection
{
	Ball *tempBall = ball_;
	double tempDirection = tempBall.dirRad;
	
	return tempDirection;
}

- (int) getBallOwner
{
	if (ball_.owner == nil)
		return -1;
	else
		return [players indexOfObject:ball_.owner];
}

- (int) getBallShooter
{
	if (ball_.shooter == nil)
		return -1;
	else
		return [players indexOfObject:ball_.shooter];
}

- (NSTimeInterval)getBallShootTime
{
	return ball_.shootTime;
}


// 주어진 인덱스의 플레이어 포지션 값을 변경한다
- (void) setPlayerPositionX:(float)x Y:(float)y At:(int)index
{
	Player *tempPlayer = [players objectAtIndex:index];
	CGPoint tempPosition = tempPlayer.position;
	if(tempPosition.x == x && tempPosition.y == y)
	{
		tempPlayer.isMoving = NO;
	}
	else
	{
		tempPlayer.isMoving = YES;
		tempPosition.x = x;
		tempPosition.y = y;
		tempPlayer.position = tempPosition;
	}
}
// 주어진 인덱스의 플레이어 방향 값을 변경한다
- (void) setPlayerDirection:(double)dir At:(int)index
{
	Player *tempPlayer = [players objectAtIndex:index];
	tempPlayer.dirRad = dir;
}

- (void) setPlayerStatus:(PlayerStatus)status At:(int)index
{
	Player *tempPlayer = [players objectAtIndex:index];
	tempPlayer.status = status;
}

// 볼의 포지션 값을 설정한다
- (void) setBallPositionX:(float)x Y:(float)y
{
	Ball *tempBall = ball_;
	CGPoint tempPosition = tempBall.position;
	if(tempPosition.x == x && tempPosition.y == y)
	{
		//tempBall.isMoving = NO;
	}
	else
	{
		tempBall.isMoving = YES;
		tempPosition.x = x;
		tempPosition.y = y;
		tempBall.position = tempPosition;
	}
}

// 볼의 방향 값을 설정한다
- (void) setBallDirection:(double)dir
{
	Ball *tempBall = ball_;
	tempBall.dirRad = dir;
}

- (void) setBallOwner:(int)index
{
	if (index != -1)
	{
//		NSTimeInterval gap = [NSDate timeIntervalSinceReferenceDate] - ball_.shootTime;
		Player *owner = [players objectAtIndex:index];
//		if ( ball_.shooter == owner && (gap < 100000) )
//			return;
		
		ball_.owner = owner;
		ball_.shooter = nil;
	}
}

- (void) setBallShooter:(int)index
{
	if (index != -1)
	{
		ball_.owner = nil;
		ball_.shooter = [players objectAtIndex:index];
		ball_.isMoving = YES;
	}
}

- (void) setGameTime:(int)frame_number
{
	if(frame_number % 10 == 0)
	{
		NSString* m = [NSString stringWithFormat:@"Time %i : ", (int)(frame_number / networkFrameRate) / 60];
		NSString* s = [NSString stringWithFormat:@"%i", (int)(frame_number / networkFrameRate) % 60];
		NSString* timeString = [m stringByAppendingFormat:s];
		
		[gameTimeView setText:timeString];
	}
}

- (void) setGoalIn:(int)goal
{
	NSString *msg;
	if(goal == 1) 
	{
		goal_teamA++;
		msg = @"Red Team Scored";
	}
	else 
	{
		goal_teamB++;
		msg = @"Blue Team Scored";
	}
	
	NSString *goalText = [NSString stringWithFormat:@"Red %i : %i Blue", goal_teamA, goal_teamB];
	
	[goalView setText:goalText];
	
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"GOAL!!" message:msg delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
	[alertView show];
	[alertView dismissWithClickedButtonIndex:0 animated:YES];
	[alertView release];
	
}

- (void) setLatencyTime:(unsigned long)time frameNumber:(int)frame_number
{
	if(frame_number % 10 == 0)
	{
		NSString *latency = [NSString stringWithFormat:@"Latency %lu ms", time];
		[latencyView setText:latency];
	}
}


@end
